package com.tuniu.agents.common.exception;

import com.tuniu.agents.common.i18n.I18nConstants;
import com.tuniu.agents.common.vo.ApiResponse;
import com.tuniu.agents.util.I18nUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * Handle general exceptions
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleException(Exception ex, HttpServletRequest request) {
        String path = request.getRequestURI();
        log.error("General error occurred at path {}: ", path, ex);
        return ApiResponse.error(9999, I18nUtil.getMessage(I18nUtil.getMessage(I18nConstants.COMMON_SYSTEM_ERROR_MESSAGE_KEY)));
    }

    /**
     * Handle custom business exceptions
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleBusinessException(BusinessException ex, HttpServletRequest request) {
        String path = request.getRequestURI();
        log.error("Business error occurred at path {}: ", path, ex);
        return ApiResponse.error(ex.getCode(), ex.getMessage());
    }
}